package com.blockmeta.bbs.minemodule.fragment;


import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.businesslibrary.base.fragment.BaseFragment;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.blockmeta.bbs.minemodule.adapter.SystemMsgAdapter;
import com.blockmeta.bbs.minemodule.pojo.SystemMessagePOJO;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import okhttp3.Call;

/**
 * 我的消息
 */
public class MyMessageFragment extends BaseFragment implements OnRefreshListener {
    private static String MESSAGE_TPYE = "message_type";
    @BindView(R2.id.rcv_msg)
    RecyclerView mRcvMsg;
    @BindView(R2.id.swipe_layout)
    SmartRefreshLayout mSwipeLayout;
    private String type;

    private int mLastId=-1;//当前数据集的最后一个数据，用于加载更多

    private List<SystemMessagePOJO> datas=new ArrayList<>();

    private SystemMsgAdapter mMsgAdapter;

    public static Fragment newInstance(String messageType) {
        MyMessageFragment fragment = new MyMessageFragment();
        Bundle bundle = new Bundle();
        bundle.putString(MESSAGE_TPYE, messageType);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public View setContentView(LayoutInflater inflater, ViewGroup container) {
        return LayoutInflater.from(mContext).inflate(R.layout.fragment_my_message, null);
    }

    @Override
    public void initView() {
        type = getArguments().getString(MESSAGE_TPYE);
        String param=String.format(Locale.getDefault(),"type=%s&device=android",type);
        mMsgAdapter = new SystemMsgAdapter(R.layout.item_push_system_message,datas);
        mRcvMsg.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL,false));
        mRcvMsg.setAdapter(mMsgAdapter);
        network(param,false);
        mSwipeLayout.setOnRefreshListener(this);
    }
    private void network(final String param, final Boolean isLoadMore){
        OkHttpUtils.get()
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.MY_MESSAGE+param)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if(mSwipeLayout==null) return;
                        if (mSwipeLayout.isRefreshing()){mSwipeLayout.finishRefresh();}
                        if (isLoadMore) {
                            mMsgAdapter.loadMoreComplete();
                        }else {
                            View view = LayoutInflater.from(mContext).inflate(R.layout.empty_net, null);
                            ImageView reconn = (ImageView) view.findViewById(R.id.click_reconn);
                            reconn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    network(param,isLoadMore);
                                }
                            });
                            mMsgAdapter.setEmptyView(view);
                        }
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        if(mSwipeLayout==null) return;
                        processResponse(response, isLoadMore);
                    }
                });
    }

    /**
     * 处理数据
     * @param response
     * @param isLoadMore
     */
    private void processResponse(String response, Boolean isLoadMore) {
        if (mSwipeLayout.isRefreshing()) {mSwipeLayout.finishRefresh();}
        if (isLoadMore) {mMsgAdapter.loadMoreComplete();}
        //空布局
        if (!isLoadMore){
            View view = LayoutInflater.from(mContext).inflate(R.layout.empty_data, null);
            mMsgAdapter.setEmptyView(view);
        }
        //解析数据
        SystemMessagePOJO[] pojo;
        try {
            pojo = new Gson().fromJson(response,SystemMessagePOJO[].class);
        }catch (Exception e){
            pojo=null;
        }

        if (pojo==null) {
            mMsgAdapter.loadMoreEnd(true);
            //在加载更多的时候判断此值如果为-1就不继续加载更的动作
            mLastId=-1;
            return;
        }
        //这里筛选出系统消息展示，目的是为了以后有了其它类型可以兼容老版本APP
        List<SystemMessagePOJO> pojos= Arrays.asList(pojo);
        Iterator<SystemMessagePOJO> iterator=pojos.iterator();
        while (iterator.hasNext()){
            SystemMessagePOJO pojo1=iterator.next();
            if (pojo1.msgType!=0){
                iterator.remove();
            }
        }
        //如果请求到的数据为空 就关闭加载更多
        int size= pojos.size();
        if (size==0) {
            mMsgAdapter.loadMoreEnd(true);
            mLastId=-1;
            return;
        }

        if (!isLoadMore) {datas.clear();}
        datas.addAll(pojos);
        mMsgAdapter.notifyDataSetChanged();
        mLastId=pojos.get(pojos.size()-1).id;
        //初始化加载更多
        if (!isLoadMore) {loadMore();}
    }

    private void loadMore() {
        mMsgAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                if (mLastId<0) {
                    mMsgAdapter.loadMoreEnd(true);
                    return;
                }
                String param=String.format(Locale.getDefault(),"type=%s&device=android&last_id=%d",type,mLastId);
                network(param,true);
            }
        },mRcvMsg);
    }

    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        String param=String.format(Locale.getDefault(),"type=%s&device=android",type);
        network(param,false);
    }
}
